﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using System.Web.Security;

namespace DataAccess
{
    public class PersonalUserDataAccess
    {
        public void CreateUser(PersonalUser user)
        {
            Database db = DatabaseFactory.CreateDatabase();

            string sql = "insert into PersonalUser values(@Id,@Password,@RealName,@TitleOfCourtesy" +
                        ",@Position,@Email,@FixPhone,@Fax,@CellPhone,@CompanyName,@ReceiveMsg)";

            DbCommand command = db.GetSqlStringCommand(sql);

            db.AddInParameter(command, "@Id", DbType.String, user.Id);
            db.AddInParameter(command, "@Password", DbType.String, 
                              FormsAuthentication.HashPasswordForStoringInConfigFile(user.Password,"SHA1"));
            db.AddInParameter(command, "@RealName", DbType.String, user.RealName);
            db.AddInParameter(command, "@TitleOfCourtesy", DbType.String, user.TitleOfCourtesy);
            db.AddInParameter(command, "@Position", DbType.String, user.Position);
            db.AddInParameter(command, "@Email", DbType.String, user.Email);
            db.AddInParameter(command, "@FixPhone", DbType.String, user.FixPhone);
            db.AddInParameter(command, "@Fax", DbType.String, user.Fax);
            db.AddInParameter(command, "@CellPhone", DbType.String, user.CellPhone);
            db.AddInParameter(command, "@CompanyName", DbType.String, user.CompanyName);
            db.AddInParameter(command, "@ReceiveMsg", DbType.Boolean, user.ReceiveMsg);

            db.ExecuteNonQuery(command);
        }

        public bool Authenticate(string userName, string userPassword)
        {
            Database db = DatabaseFactory.CreateDatabase();

            string sql = "select count(*) from Users where Id=@Id and Password=@Password";

            DbCommand cmd = db.GetSqlStringCommand(sql);

            db.AddInParameter(cmd, "@Id", DbType.String, userName);
            db.AddInParameter(cmd, "@Password", DbType.String, 
                            FormsAuthentication.HashPasswordForStoringInConfigFile(userPassword,"SHA1"));

            if (db.ExecuteScalar(cmd).ToString() == "1")
                return true;
            return false;

        }
    }
}
